﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Windows;
using MahApps.Metro.Controls;
using User;

namespace FrameworkTemplate.Windows
{
    /// <summary>
    /// Interaction logic for AccountManager.xaml
    /// </summary>
    public partial class AccountManager : MetroWindow
    {
        readonly static string password_pattern = @"\w+";
        readonly Regex password_regex;
        Account account;
        Dictionary<string, Account> account_datas;
        public AccountManager(ref Account account)
        {
            InitializeComponent();
            password_regex = new Regex(password_pattern, RegexOptions.IgnoreCase);
            this.account = account;
            account_datas = EncryptManager.ReadUserData();
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //刷新用户名到下拉框
            username.Items.Clear();
            foreach (var kvp in account_datas)
            {
                if (kvp.Value.right == Right.Ruler&&account.right < Right.Ruler)
                    continue;
                username.Items.Add(kvp.Key);
            }
            username.SelectedIndex = 0;
            //username_comboBox.SelectedIndex = username_comboBox.Items.Count - 1;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Confirm_Click(object sender, RoutedEventArgs e)
        {
            string name = username.SelectedItem as string;
            if (account.right > account_datas[name].right||
                EncryptManager.VertityPassword(account_datas[name], old_password.Password))
            {
                var np = new_password.Password;
                var cp = confirm_password.Password;
                Match password_match = password_regex.Match(np);
                if(!password_match.Success)
                {
                    password_warn_msg.Text = System.Windows.Application.Current.FindResource("password_format_wrong") as string;
                    return;
                }
                if (np != cp)
                {
                    password_warn_msg.Text = System.Windows.Application.Current.FindResource("password_confirm_not_match") as string;
                    return;
                }
                else
                {
                    EncryptManager.ChangePassword(account_datas[name], cp);
                    EncryptManager.SaveUserData(account_datas);
                    password_warn_msg.Text = System.Windows.Application.Current.FindResource("password_change_success") as string;
                }

            }
            else
            {
                password_warn_msg.Text = System.Windows.Application.Current.FindResource("password_wrong") as string;
            }
        }
    }
}
